package com.feishi.core.util.http;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.util.Map;

import static com.feishi.core.util.http.HttpUtil.buildGet;
import static com.feishi.core.util.http.HttpUtil.buildPost;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: caixq
 * Date: 2018-11-28
 * Time: 上午10:34
 */
public class HttpBuild {
    private HttpRequestBase httpRequest;
    private BasicCredentialsProvider provider;

    public HttpBuild newInstance(){
        return new HttpBuild();
    }

    public HttpBuild get(String url) throws Exception {
        return get(url,null,null);
    }
    public HttpBuild get(String url, Map<String,String> values) throws Exception {
        return get(url,values,null);
    }
    public HttpBuild get(String url, Map<String,String> values, Map<String,String> header) throws Exception {
        this.httpRequest=buildGet(url,values,header);
        return this;
    }
    public HttpBuild post(String url) throws Exception {
        return post(url,null,null,null);
    }
    public HttpBuild post(String url, Map<String,String> values) throws Exception {
        return post(url,values,null,null);
    }
    public HttpBuild post(String url, String content, Map<String,String> header) throws Exception {
        return post(url,null,content,header);
    }
    public HttpBuild post(String url, Map<String,String> values, Map<String,String> header) throws Exception {
        return post(url,values,null,header);
    }
    public HttpBuild post(String url, Map<String,String> values, String content, Map<String,String> header) throws Exception {
        this.httpRequest=buildPost(url,values,content,header);
        return this;
    }

    public HttpBuild basicAuth(String name, String password) throws Exception {
        this.provider = new BasicCredentialsProvider();
        // Create the authentication scope
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        // Create credential pair，在此处填写用户名和密码
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(name, password);
        // Inject the credentials
        provider.setCredentials(scope, credentials);
        return this;
    }

    public String send() throws IOException {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(provider);
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        return HttpUtil.sendRequest(closeableHttpClient,httpRequest);
    }



    public static void main(String[] args){
    }
}
